package com.gzdh.dishrecognition.ui.fragment;

import static com.gzdh.dishrecognition.MainActivity.ISCONNECT;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.gzdh.dishrecognition.MainActivity;
import com.gzdh.dishrecognition.R;
import com.gzdh.dishrecognition.config.ProductConst;
import com.gzdh.dishrecognition.config.SysConstConfig;
import com.gzdh.dishrecognition.emu.ModelEmus;
import com.gzdh.dishrecognition.emu.PeripheralDeviceEmus;
import com.gzdh.dishrecognition.emu.PrintDevEmus;
import com.gzdh.dishrecognition.emu.ReadCardTypeEmus;
import com.gzdh.dishrecognition.event.CartEvent;
import com.gzdh.dishrecognition.ui.dialog.InputDialog;
import com.gzdh.dishrecognition.ui.dialog.MsgDialog;
import com.gzdh.dishrecognition.ui.view.OptionItemView;
import com.gzdh.dishrecognition.util.print.PrintUtil;

import net.posprinter.posprinterface.TaskCallback;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

public class BaseSysSettingFragment extends Fragment {


    private Context mContext;

    private Activity activity;

    private OptionItemView hideDinnerBut;

    private OptionItemView autoDinnerBut;

    private OptionItemView allowPreDinBut;

    private OptionItemView kuacanBut;

    private OptionItemView scanTakeBut;

    private OptionItemView selectModelBut;

    private OptionItemView fixedAmountBut;

    private OptionItemView fixedAutoPayBut;

    private OptionItemView selectDeviceBut;

    private OptionItemView printDeviceBut;

    private OptionItemView printTextSizeBut;

    private OptionItemView printWidthPixelBut;

    private OptionItemView printMiddleLocationBut;

    private OptionItemView printProductNameEnterBut;

    private OptionItemView testPrintDeviceBut;

    private OptionItemView autoLoginBut;


    public BaseSysSettingFragment(Activity activity) {
        this.activity = activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.fragment_base_setting, container, false);
        mContext = view.getContext();

        hideDinnerBut = view.findViewById(R.id.hideDinnerBut);
        hideDinnerBut.setOnClickListener(view1 -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("隐藏餐次");
            final Map<String, Boolean> map = new LinkedHashMap<>();
            map.put("开启", true);
            map.put("关闭", false);
            final String[] keysTemp = new String[2];
            final String[] keys = map.keySet().toArray(keysTemp);
            builder.setItems(keys, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    boolean state = map.get(keys[which]);
                    SysConstConfig.getInstance().setHideDinner(state);
                    showState();
                }
            });
            builder.show();
        });


        selectModelBut = view.findViewById(R.id.selectModelBut);
        selectModelBut.setOnClickListener(view1 -> {
            ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
            EventBus.getDefault().post(new CartEvent());
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("界面模式");
            final Map<String, Integer> map = new LinkedHashMap<>();
            for (ModelEmus goo : ModelEmus.values()) {
                map.put(goo.getName(), goo.getValue());
            }
            final String[] keysTemp = new String[ModelEmus.values().length];
            final String[] keys = map.keySet().toArray(keysTemp);
            builder.setItems(keys, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int state = map.get(keys[which]);
                    SysConstConfig.getInstance().setSurfaceModel(ModelEmus.getByValue(state));
                    showState();
                }
            });
            builder.show();
        });

        fixedAmountBut = view.findViewById(R.id.fixedAmountBut);
        fixedAmountBut.setOnClickListener(v -> {
            InputDialog inputDialog = new InputDialog(mContext);
            inputDialog.show();
            inputDialog.getMsgTv().setText("请输入消费金额");
            inputDialog.getEditText().setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
            inputDialog.getEditText().setText(String.valueOf(SysConstConfig.getInstance().getFixedAmount()));
            inputDialog.getOkTv().setOnClickListener(view1 -> {
                String row = inputDialog.getEditText().getText().toString();
                if (!"".equals(row)) {
                    BigDecimal amount = new BigDecimal(row).setScale(2, RoundingMode.DOWN);
                    SysConstConfig.getInstance().setFixedAmount(amount.toPlainString());
                    inputDialog.dismiss();
                    showState();
                } else {
                    Toast.makeText(mContext, "输入有误，请重新输入", Toast.LENGTH_LONG).show();
                }
            });
        });

        fixedAutoPayBut = view.findViewById(R.id.fixedAutoPayBut);
        fixedAutoPayBut.setOnClickListener(view1 -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("固定消费自动扣款");
            final Map<String, Boolean> map = new LinkedHashMap<>();
            map.put("开启", true);
            map.put("关闭", false);
            final String[] keysTemp = new String[2];
            final String[] keys = map.keySet().toArray(keysTemp);
            builder.setItems(keys, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    boolean state = map.get(keys[which]);
                    SysConstConfig.getInstance().setFixedAutoPay(state);
                    showState();
                }
            });
            builder.show();
        });

        selectDeviceBut = view.findViewById(R.id.selectDeviceBut);
        selectDeviceBut.setOnClickListener(view1 -> {
            ProductConst.getInstance().setProductCartModelList(new ArrayList<>());
            EventBus.getDefault().post(new CartEvent());
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("请选择外围设备");
            final Map<String, Integer> map = new LinkedHashMap<>();
            for (PeripheralDeviceEmus goo : PeripheralDeviceEmus.values()) {
                map.put(goo.getName(), goo.getValue());
            }
            final String[] keysTemp = new String[PeripheralDeviceEmus.values().length];
            final String[] keys = map.keySet().toArray(keysTemp);
            builder.setItems(keys, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int state = map.get(keys[which]);
                    if (PeripheralDeviceEmus.getByValue(state) != PeripheralDeviceEmus.defaultType &&
                            SysConstConfig.getInstance().getReadCardType() == ReadCardTypeEmus.cardSQ) {
                        //提示不支持，继续确定将恢复卡序列
                        MsgDialog msgDialog = new MsgDialog(mContext);
                        msgDialog.show();
                        msgDialog.showMsg("该模式仅支持读卡序列号，请核对再操作");

                    } else {
                        SysConstConfig.getInstance().setPeripheralDeviceModel(PeripheralDeviceEmus.getByValue(state));
                        showState();
                        EventBus.getDefault().post(new CartEvent());
                    }

                }
            });
            builder.show();
        });

        allowPreDinBut = view.findViewById(R.id.allowPreDinBut);
        allowPreDinBut.setOnClickListener(view1 -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("允许副屏点餐");
            final Map<String, Boolean> map = new LinkedHashMap<>();
            map.put("开启", true);
            map.put("关闭", false);
            final String[] keysTemp = new String[2];
            final String[] keys = map.keySet().toArray(keysTemp);
            builder.setItems(keys, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    boolean state = map.get(keys[which]);
                    SysConstConfig.getInstance().setAllowPreDin(state);
                    showState();
                }
            });
            builder.show();
        });


        autoDinnerBut = view.findViewById(R.id.autoDinnerBut);
        autoDinnerBut.setOnClickListener(view1 -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("自动餐次");
            final Map<String, Boolean> map = new LinkedHashMap<>();
            map.put("开启", true);
            map.put("关闭", false);
            final String[] keysTemp = new String[2];
            final String[] keys = map.keySet().toArray(keysTemp);
            builder.setItems(keys, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    boolean state = map.get(keys[which]);
                    SysConstConfig.getInstance().setAutoDinner(state);
                    showState();
                }
            });
            builder.show();
        });

        autoLoginBut=view.findViewById(R.id.autoLoginBut);
        autoLoginBut.setOnClickListener(view1 -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("自动登陆");
            final Map<String, Boolean> map = new LinkedHashMap<>();
            map.put("开启", true);
            map.put("关闭", false);
            final String[] keysTemp = new String[2];
            final String[] keys = map.keySet().toArray(keysTemp);
            builder.setItems(keys, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    boolean state = map.get(keys[which]);
                    SysConstConfig.getInstance().setAutoLogin(state);
                    showState();
                }
            });
            builder.show();
        });

        kuacanBut = view.findViewById(R.id.kuacanBut);
        kuacanBut.setOnClickListener(view1 -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("允许跨餐次点餐");
            final Map<String, Boolean> map = new LinkedHashMap<>();
            map.put("开启", true);
            map.put("关闭", false);
            final String[] keysTemp = new String[2];
            final String[] keys = map.keySet().toArray(keysTemp);
            builder.setItems(keys, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    boolean state = map.get(keys[which]);
                    SysConstConfig.getInstance().setKuacan(state);
                    showState();
                }
            });
            builder.show();
        });

        scanTakeBut = view.findViewById(R.id.scanTakeBut);
        scanTakeBut.setOnClickListener(view1 -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("允许扫码领餐");
            final Map<String, Boolean> map = new LinkedHashMap<>();
            map.put("开启", true);
            map.put("关闭", false);
            final String[] keysTemp = new String[2];
            final String[] keys = map.keySet().toArray(keysTemp);
            builder.setItems(keys, (dialog, which) -> {
                boolean state = Boolean.TRUE.equals(map.get(keys[which]));
                SysConstConfig.getInstance().setScanTake(state);
                showState();
                EventBus.getDefault().post(new CartEvent());
            });
            builder.show();
        });

        printDeviceBut = view.findViewById(R.id.printDeviceBut);
        printDeviceBut.setOnClickListener(view1 -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("小票打印机设置");
            final Map<String, Integer> map = new LinkedHashMap<>();
            for (PrintDevEmus goo : PrintDevEmus.values()) {
                map.put(goo.getName(), goo.getValue());
            }
            final String[] keysTemp = new String[PrintDevEmus.values().length];
            final String[] keys = map.keySet().toArray(keysTemp);
            builder.setItems(keys, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int state = map.get(keys[which]);
                    SysConstConfig.getInstance().setPrintDevEmus(PrintDevEmus.getByValue(state));
                    if (SysConstConfig.getInstance().getPrintDevEmus() == PrintDevEmus.print58) {
                        SysConstConfig.getInstance().setPrintWidthPixel(384);
                        SysConstConfig.getInstance().setPrintMiddleLocation(192);
                        SysConstConfig.getInstance().setPrintTextSize(0);
                        SysConstConfig.getInstance().setPrintProductNameEnter(384 / 2);
                    } else {
                        SysConstConfig.getInstance().setPrintWidthPixel(570);
                        SysConstConfig.getInstance().setPrintMiddleLocation(380);
                        SysConstConfig.getInstance().setPrintTextSize(0);
                        SysConstConfig.getInstance().setPrintProductNameEnter(570 / 3);
                    }
                    showState();
                }
            });
            builder.show();
        });


        printTextSizeBut = view.findViewById(R.id.printTextSizeBut);
        printTextSizeBut.setOnClickListener(view2 -> {
            //字体大小设置
            InputDialog inputDialog = new InputDialog(mContext);
            inputDialog.show();
            inputDialog.getMsgTv().setText("请输入打印字体大小");
            inputDialog.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
            inputDialog.getEditText().setText(String.valueOf(SysConstConfig.getInstance().getPrintTextSize()));
            inputDialog.getOkTv().setOnClickListener(view1 -> {
                String row = inputDialog.getEditText().getText().toString();
                if (!"".equals(row)) {
                    int rowInt = Integer.parseInt(row);
                    SysConstConfig.getInstance().setPrintTextSize(rowInt);
                    inputDialog.dismiss();
                    showState();

                } else {
                    Toast.makeText(mContext, "输入有误，请重新输入", Toast.LENGTH_LONG).show();
                }
            });
        });
        printWidthPixelBut = view.findViewById(R.id.printWidthPixelBut);
        printWidthPixelBut.setOnClickListener(view2 -> {
            //字体大小设置
            InputDialog inputDialog = new InputDialog(mContext);
            inputDialog.show();
            inputDialog.getMsgTv().setText("请输入打印机纸的相对宽度");
            inputDialog.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
            inputDialog.getEditText().setText(String.valueOf(SysConstConfig.getInstance().getPrintWidthPixel()));
            inputDialog.getOkTv().setOnClickListener(view1 -> {
                String row = inputDialog.getEditText().getText().toString();
                if (!"".equals(row)) {
                    int rowInt = Integer.parseInt(row);
                    SysConstConfig.getInstance().setPrintWidthPixel(rowInt);
                    inputDialog.dismiss();
                    showState();

                } else {
                    Toast.makeText(mContext, "输入有误，请重新输入", Toast.LENGTH_LONG).show();
                }
            });
        });


        printMiddleLocationBut = view.findViewById(R.id.printMiddleLocationBut);
        printMiddleLocationBut.setOnClickListener(view2 -> {
            //字体大小设置
            InputDialog inputDialog = new InputDialog(mContext);
            inputDialog.show();
            inputDialog.getMsgTv().setText("请输入打印中间字段绝对位置");
            inputDialog.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
            inputDialog.getEditText().setText(String.valueOf(SysConstConfig.getInstance().getPrintMiddleLocation()));
            inputDialog.getOkTv().setOnClickListener(view1 -> {
                String row = inputDialog.getEditText().getText().toString();
                if (!"".equals(row)) {
                    int rowInt = Integer.parseInt(row);
                    SysConstConfig.getInstance().setPrintMiddleLocation(rowInt);
                    inputDialog.dismiss();
                    showState();

                } else {
                    Toast.makeText(mContext, "输入有误，请重新输入", Toast.LENGTH_LONG).show();
                }
            });
        });


        printProductNameEnterBut = view.findViewById(R.id.printProductNameEnterBut);
        printProductNameEnterBut.setOnClickListener(view2 -> {
            //字体大小设置
            InputDialog inputDialog = new InputDialog(mContext);
            inputDialog.show();
            inputDialog.getMsgTv().setText("请输入打印商品名换行尺寸");
            inputDialog.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
            inputDialog.getEditText().setText(String.valueOf(SysConstConfig.getInstance().getPrintProductNameEnter()));
            inputDialog.getOkTv().setOnClickListener(view1 -> {
                String row = inputDialog.getEditText().getText().toString();
                if (!"".equals(row)) {
                    int rowInt = Integer.parseInt(row);
                    SysConstConfig.getInstance().setPrintProductNameEnter(rowInt);
                    inputDialog.dismiss();
                    showState();

                } else {
                    Toast.makeText(mContext, "输入有误，请重新输入", Toast.LENGTH_LONG).show();
                }
            });
        });


        testPrintDeviceBut = view.findViewById(R.id.testPrintDeviceBut);
        testPrintDeviceBut.setOnClickListener(view1 -> {
            try {
                PrintUtil pUtil = new PrintUtil();
                pUtil.printAlignment(1);
                if (SysConstConfig.getInstance().getPrintDevEmus() == PrintDevEmus.print58) {
                    pUtil.printText("********************************");
                } else {
                    pUtil.printText("************************************************");
                }
                pUtil.printLine();
                pUtil.printText("**************  膳 食 订 餐 系 统  *************");
                pUtil.printLine();
                if (SysConstConfig.getInstance().getPrintDevEmus() == PrintDevEmus.print58) {
                    pUtil.printText("********************************");
                } else {
                    pUtil.printText("************************************************");
                }
                pUtil.setTextSize(SysConstConfig.getInstance().getPrintTextSize());
                pUtil.printLine();
                pUtil.printText("当你看到此消息时，打印测试成功");
                pUtil.printLine();
                pUtil.printText("当前时间：" + new Date());
                pUtil.printLine();
                pUtil.printText("广州市鼎鸿电子科技有限公司");
                pUtil.printLine();
                pUtil.setTextSize(0);
                if (SysConstConfig.getInstance().getPrintDevEmus() == PrintDevEmus.print58) {
                    pUtil.printText("********************************");
                } else {
                    pUtil.printText("************************************************");
                }
                pUtil.printLine(4);
                pUtil.printQZ();
                if (ISCONNECT) {
                    MainActivity.myBinder.Write(pUtil.getOutbyte(), new TaskCallback() {
                        @Override
                        public void OnSucceed() {
                            Toast.makeText(mContext, "打印成功", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void OnFailed() {
                            Toast.makeText(mContext, "打印失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        });


        showState();

        return view;
    }

    private void showState() {
        if (SysConstConfig.getInstance().isHideDinner()) {
            hideDinnerBut.setRightText("开启");
        } else {
            hideDinnerBut.setRightText("关闭");
        }

        if (SysConstConfig.getInstance().isKuacan()) {
            kuacanBut.setRightText("开启");
        } else {
            kuacanBut.setRightText("关闭");
        }

        if (SysConstConfig.getInstance().isScanTake()) {
            scanTakeBut.setRightText("开启");
        } else {
            scanTakeBut.setRightText("关闭");
        }

        if (SysConstConfig.getInstance().isAutoDinner()) {
            autoDinnerBut.setRightText("开启");
        } else {
            autoDinnerBut.setRightText("关闭");
        }

        if (SysConstConfig.getInstance().isAllowPreDin()) {
            allowPreDinBut.setRightText("开启");
        } else {
            allowPreDinBut.setRightText("关闭");
        }


        if (SysConstConfig.getInstance().isAutoLogin()) {
            autoLoginBut.setRightText("开启");
        } else {
            autoLoginBut.setRightText("关闭");
        }

        selectDeviceBut.setRightText(SysConstConfig.getInstance().getPeripheralDeviceModel().getName());
        switch (SysConstConfig.getInstance().getSurfaceModel()) {
            case defaultType:
                selectModelBut.setRightText(ModelEmus.defaultType.getName());
                break;
            case numberType:
                selectModelBut.setRightText(ModelEmus.numberType.getName());
                break;
            case fixedType:
                selectModelBut.setRightText(ModelEmus.fixedType.getName());
                break;
            case idfType:
                selectModelBut.setRightText(ModelEmus.idfType.getName());
                break;
        }
        printDeviceBut.setRightText(SysConstConfig.getInstance().getPrintDevEmus().getName());

        printTextSizeBut.setRightText(String.valueOf(SysConstConfig.getInstance().getPrintTextSize()));
        printWidthPixelBut.setRightText(String.valueOf(SysConstConfig.getInstance().getPrintWidthPixel()));
        printMiddleLocationBut.setRightText(String.valueOf(SysConstConfig.getInstance().getPrintMiddleLocation()));
        printProductNameEnterBut.setRightText(String.valueOf(SysConstConfig.getInstance().getPrintProductNameEnter()));
        fixedAmountBut.setRightText(String.valueOf(SysConstConfig.getInstance().getFixedAmount()));
        if (SysConstConfig.getInstance().isFixedAutoPay()) {
            fixedAutoPayBut.setRightText("开启");
        } else {
            fixedAutoPayBut.setRightText("关闭");
        }
        if(SysConstConfig.getInstance().getSurfaceModel() == ModelEmus.fixedType) {
            fixedAmountBut.setVisibility(View.VISIBLE);
            fixedAutoPayBut.setVisibility(View.VISIBLE);
        } else {
            fixedAmountBut.setVisibility(View.GONE);
            fixedAutoPayBut.setVisibility(View.GONE);
        }
    }

}